package com.example.jpa.crud.configuration;

import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class CrudWebMvcConfigurer implements WebMvcConfigurer {

    private static final String DOT = ".";

    private static final String DEFAULT_PATH_PREFIX = "api";

    private final CrudConfiguration crudConfiguration;

    public CrudWebMvcConfigurer(CrudConfiguration crudConfiguration) {
        this.crudConfiguration = crudConfiguration;
    }

    @SuppressWarnings("all")
    @Override
    public void configurePathMatch(PathMatchConfigurer object) {
        if (Boolean.TRUE.equals(crudConfiguration.getRemovePathPrefix())) {
            return;
        }
        final String packageName = this.getClass().getPackage().getName();
        final int index = packageName.lastIndexOf(DOT);
        final String controllerPackageName = index == -1 ? packageName : packageName.substring(0, index);
        final String pathPrefix = crudConfiguration.getPathPrefix();
        final String value = (pathPrefix == null || !StringUtils.hasText(pathPrefix)) ? DEFAULT_PATH_PREFIX : pathPrefix;
        object.addPathPrefix(value, clazz -> {
            if (clazz == null) {
                return false;
            }
            return clazz.getName().startsWith(controllerPackageName);
        });
    }

}
